var express = require('express');
var router = express.Router();
var Promise = require('promise');
var accountService = require('./service/AccountService');
var fansService = require('./service/FansService');
var wechatRest = require('../utils/wechatRest');
var interceptor = require('../utils/interceptor');
var common = require('../utils/commonUtils');
var logger = require('log4js').getLogger('wechat.js');
var conf = require('../../config');

router.get('/auth/:authType',function(req, res, next){
	var authType = req.params.authType;
	var code = req.query.code;
	var state = req.query.state;
	var account = req.session.account;
	Promise.resolve(account).then(function (account) {
		if (!account) {
			return accountService.getDefaultAccount().then(function (r) {
				account = r;
				req.session.account = r;
				return Promise.resolve(r);
			});
			return Promise.resolve(account);
		}
	}).then(function(account){
		if (code == 'authdeny') {
		  // 取消授权
		  res.status(200).end();
		} else if (code) {
		  // code换取openid
		  return wechatRest.auth(account.appId, account.appSecret, code).then(function(result){
			  logger.info("wechat auth openid is "+result.openid);
				if (req.session.authScope == conf.wechat.userScope) {
				    return fansService.snsFansSaveOrUpdate(result.openid, account.id, result.access_token);
				} else {
					return fansService.snsFansGetByOpenId(result.openid);
				}				
			});
		} else {
			return Promise.resolve(null);
		}
	}).done(function(fans){

		if(fans){
		   req.session.fans = fans;
	       res.redirect(state);
		}else{		  
          // 未拿到粉丝信息，重新请求授权
          if (authType == 'base') {
            req.session.authScope = conf.wechat.baseScope;
          } else {
            req.session.authScope = conf.wechat.userScope;
          }
          var redirectUri = '/wechat/auth/'+authType;
			//var returnUrl = req.session.backUrl || state;
          res.redirect(wechatRest.getRedirectUrls(req.session.account, redirectUri,
			  req.session.authScope, state));
		} 		  
	},function(err){
		logger.error('auth2:',req.session);
		logger.error('auth3:', err);
		res.status(500).end();
	});

});

router.get('/jssdkSign', function(req,res,next){
	//url = "http://m.muzhibuluo.com/h5/2cat/startup.html?code=123";
	var url = req.query.url;
	if(common.isUrl(url)){
		var urlSplit = url.split('/');
		if(urlSplit.length>1&&urlSplit[2].indexOf("m.muzhibuluo.com")>=0){
			next();
			return;
		}
	}
	res.json({success:false});
	return;
},interceptor.verifyJsTicket,function(req,res){
	var url = req.query.url;
	var account = req.session.account||{};
	if(url&&account.jsTicket){
		var ret = wechatRest.sign(req.session.account.jsTicket, url);
		var data = {appId: req.session.account.appId, // 微信签名参数
			timestamp: ret.timestamp,
			nonceStr: ret.nonceStr,
			signature: ret.signature};
		res.json({success:true,data:data});
	}else{
		res.json({success:false});
	}

});



module.exports = router;